﻿using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Aliyun.OSS;
using Aliyun.OSS.Common;

namespace BUGCOME.Infrastructure.Helper
{
    /// <summary>阿里云OSS操作工具类（兼容旧版SDK）</summary>
    public static class AliyunOssHelper
    {
        /// <summary>
        /// 上传文件流到OSS
        /// </summary>
        /// <param name="stream">待上传流</param>
        /// <param name="objectName">OSS存储名</param>
        /// <param name="contentType">内容类型（预留）</param>
        /// <param name="settings">OSS配置</param>
        /// <returns>HTTP状态码</returns>
        public static HttpStatusCode PutObjectFromFile(Stream stream, string objectName, string contentType, AliOssSettings settings)
        {
            // 校验入参
            if (stream == null) throw new ArgumentNullException(nameof(stream), "上传流不能为空");
            if (settings == null) throw new ArgumentNullException(nameof(settings), "OSS配置不能为空");
            if (string.IsNullOrWhiteSpace(objectName)) throw new ArgumentException("存储文件名不能为空", nameof(objectName));

            var client = new OssClient(settings.Endpoint, settings.AccessKeyId, settings.AccessKeySecret);

            try
            {
                stream.Position = 0; // 重置流位置
                var request = new PutObjectRequest(settings.BucketName, objectName, stream);
                var result = client.PutObject(request);
                return result.HttpStatusCode;
            }
            catch (Exception)
            {
                return HttpStatusCode.InternalServerError;
            }
        }

        /// <summary>
        /// 异步删除OSS文件
        /// </summary>
        /// <param name="settings">OSS配置</param>
        /// <param name="objectName">文件名</param>
        /// <returns>是否成功</returns>
        public static async Task<bool> DeleteObjectAsync(AliOssSettings settings, string objectName)
        {
            // 校验入参
            if (settings == null) throw new ArgumentNullException(nameof(settings));
            if (string.IsNullOrWhiteSpace(objectName)) return false;

            var client = new OssClient(settings.Endpoint, settings.AccessKeyId, settings.AccessKeySecret);

            try
            {
                // 旧版无原生异步，用Task.Run包装
                await Task.Run(() => client.DeleteObject(settings.BucketName, objectName));
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 异步获取OSS文件流
        /// </summary>
        /// <param name="settings">OSS配置</param>
        /// <param name="objectName">文件名</param>
        /// <returns>文件流（null表示失败）</returns>
        public static async Task<Stream> GetObjectStreamAsync(AliOssSettings settings, string objectName)
        {
            // 校验入参
            if (settings == null) throw new ArgumentNullException(nameof(settings));
            if (string.IsNullOrWhiteSpace(objectName)) return null;

            var client = new OssClient(settings.Endpoint, settings.AccessKeyId, settings.AccessKeySecret);

            try
            {
                var ossObject = await Task.Run(() => client.GetObject(settings.BucketName, objectName));
                var memoryStream = new MemoryStream();
                await ossObject.Content.CopyToAsync(memoryStream);
                memoryStream.Position = 0; // 重置流位置
                return memoryStream;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}